<template>
	<div class="app-container">
		<jk-operation-card ref="box1" class="margin-bottom-10">
			<div class="flex-between-center-wrap">
				<div class="flex-start-center-wrap">
					<el-radio-group v-model="searchParams.repairState" @change="onStateChange">
						<el-radio-button v-for="(item, index) in repairStateList" :key="index" :label="item.id">
							<el-badge v-if="item.count" :value="item.count" :max="99">
								<span class="margin-right-20">{{ item.name }}</span>
							</el-badge>
							<span v-else class="margin-right-10">{{ item.name }}</span>
						</el-radio-button>
					</el-radio-group>
					<!--<jk-add-button :permission-prefix="prefix" class="margin-5-0 item-gap" @click="onAddBtn"></jk-add-button>-->
				</div>
				<div class="flex-end-center-wrap">
					<jk-search-input v-model="searchParams.machineNameOrCode" placeholder="设备编号或名称" size="small" class="search-bar-item-size2 margin-5-0 item-gap" clearable @on-enter="onSearchBtn" />
					<jk-search-input v-model="searchParams.code" placeholder="维修单号" size="small" class="search-bar-item-size3 margin-5-0 item-gap" clearable @on-enter="onSearchBtn" />
					<jk-search-button @click="onSearchBtn"></jk-search-button>
				</div>
			</div>
		</jk-operation-card>

		<jk-card>
			<jk-table ref="jkTable" :loading="tableLoading" :data="tableData" :height="tableHeight + 20">
				<vxe-column
					v-for="(item, index) in tableColumnList"
					:key="index"
					:title="item.title"
					:align="item.align"
					:field="item.keyName"
					:sortable="item.sortable"
					:fixed="item.fixed ? item.fixed : ''"
					:min-width="item.minWidth"
					:width="item.width"
				>
					<template slot-scope="scope">
						<repair-state-bar v-if="item.keyName === 'repairState'" :status="scope.row.repairState"></repair-state-bar>
						<span v-else>{{ scope.row[item.keyName] }}</span>
					</template>
				</vxe-column>
				<vxe-column title="操作" align="center" fixed="right" :width="240">
					<template slot-scope="scope">
						<div class="flex-center">
							<jk-button :has-permission="getPermission([`${prefix}:update`])" :disabled="scope.row.repairState !== 0 || !getPermission([`${prefix}:update`])" type="primary" class="item-gap" size="mini" @click="onTakingBtn(scope.row)">接单</jk-button>
							<jk-button :has-permission="getPermission([`${prefix}:update`])" :disabled="scope.row.repairState !== 1 || !getPermission([`${prefix}:update`])" type="success" class="item-gap" size="mini" @click="onEndBtn(scope.row)">完成</jk-button>
							<el-dropdown trigger="click" @command="onDropdownChange($event, scope.row)">
								<el-button type="primary" size="mini" class="el-dropdown-link">
									更多<i class="el-icon-arrow-down el-icon--right"></i>
								</el-button>
								<el-dropdown-menu slot="dropdown">
									<el-dropdown-item
										v-for="(item) in dropdownOption"
										:key="item.code"
										:command="item.code"
										:divided="item.divided"
										:disabled="item.allowState || item.allowState === 0 ? scope.row.repairState !== item.allowState : false"
										:style="{
											'display': !item.isShow ? 'none' : 'block',
											'text-decoration': getPermission([`${prefix}:${item.permissionName}`]) ? '' : 'line-through'
										}"
									>
										<span :class="`${item.icon} item-gap`"></span>
										<span>{{ item.name }}</span>
									</el-dropdown-item>
								</el-dropdown-menu>
							</el-dropdown>
						</div>
					</template>
				</vxe-column>
			</jk-table>

			<!-- 分页组件 -->
			<footer ref="box2" class="flex-end-center margin-top-10">
				<jk-page
					:page-index="searchParams.pageNo"
					:page-sizes="searchParams.pageSizes"
					:page-size="searchParams.pageSize"
					:total="totalCount"
					@on-change="onPageChange"
				/>
			</footer>
		</jk-card>
		<detail-dialog
			:data-id="dataId"
			:dialog-state="detailDialogState"
			@on-visible-change="onVisibleChangeOfDetailDialog"
		></detail-dialog>
		<save-dialog
			:data-id="dataId"
			:dialog-state="saveDialogState"
			@on-visible-change="onVisibleChange"
			@on-finish="onFinish"
		></save-dialog>
	</div>
</template>

<script>
    import detailDialog from './detail-dialog';
    import calHeight from '/src/mixins/cal-table-height';
    import { pageConfig, tipsBar } from '/src/utils/jk/jk-tool';
    import getMenuColumn from '../../../../mixins/getMenuColumn';
    import handlerCache from '../../../../mixins/handler-cache';
    import { repairStateList } from '../../../../utils/jk/status-option-list';
    import {
        machineManagerRepairOrderClearComplete,
        machineManagerRepairOrderClearTaking, machineManagerRepairOrderDelete,
        machineManagerRepairOrderGetStateCount,
        machineManagerRepairOrderPage,
        machineManagerRepairOrderTaking
    } from '../../../../api/machine/repairOrder';
    import repairStateBar from './components/repair-state-bar';
    import saveDialog from './save-dialog';
    import permissionMixin from '../../../../mixins/permission-mixin';
    export default {
        name: 'RepairOrder',
        components: {
            saveDialog,
            repairStateBar,
            detailDialog
        },
        mixins: [calHeight, getMenuColumn, handlerCache, permissionMixin],
        data() {
            return {
                prefix: 'machinemanager:repairOrder',
                apiItem: {
                    'page': machineManagerRepairOrderPage
                },
                dataItem: {},
                repairStateList: repairStateList,
                detailDialogState: false,
                dataId: null,
                saveDialogState: false,
                tableLoading: true,
                tableData: [],
                totalCount: 0,
                searchParams: {
                    pageNo: 1,
                    pageSize: pageConfig.pageSize,
                    machineNameOrCode: '',
                    repairState: 0,
                    code: ''
                },
                dropdownOption: [
                    { code: 'QUERY', name: '详情', isShow: true, permissionName: 'query', icon: 'el-icon-view', allowState: null, api: null },
                    { code: 'CANCEL_TAKING', name: '取消接单', isShow: true, permissionName: 'update', divided: true, icon: 'el-icon-circle-close', allowState: 1, api: machineManagerRepairOrderClearTaking },
                    { code: 'CANCEL_COMPLETE', name: '撤销完成', permissionName: 'update', isShow: true, icon: 'el-icon-close', allowState: 2, api: machineManagerRepairOrderClearComplete },
                    { code: 'DELETE', name: '删除', isShow: true, permissionName: 'delete', icon: 'el-icon-delete', allowState: 0, api: machineManagerRepairOrderDelete }
                ]
            };
        },
        methods: {
            onStateChange() {
                this.$set(this.searchParams, 'pageNo', 1);
                this.getListRequest();
            },
            onEndBtn(row) {
                // 完成维修
                this.dataId = row.id;
                this.saveDialogState = true;
            },
            onDropdownChange(type, row) {
                const optionItem = this.dropdownOption.find(x => x.code === type);
                if (this.getPermission([`${this.prefix}:${optionItem.permissionName}`])) {
                    if (optionItem) {
                        if (optionItem.code === 'QUERY') {
                            this.dataId = row.id;
                            this.detailDialogState = true;
                        } else if (optionItem.code === 'COMPLETE') {
                            // 完成维修
                            this.dataId = row.id;
                            this.saveDialogState = true;
                        } else {
                            this.$confirm(`确定"${optionItem.name}"吗？`, '提示', { type: 'warning' }).then(() => {
                                optionItem.api({ id: row.id }).then(res => {
                                    if (res.data.status === 200) {
                                        this.getListRequest();
                                    }
                                });
                            }).catch(() => {});
                        }
                    }
                } else {
                    tipsBar(this, 'custom', 'warning', '无操作权限!');
                }
            },
            onTakingBtn(row) {
                this.$confirm('是否接单吗?', { type: 'warning' }).then(() => {
                    if (row.repairState === 0) {
                        return machineManagerRepairOrderTaking({ id: row.id });
                    } else if (row.repairState === 1) {
                        return machineManagerRepairOrderClearTaking({ id: row.id });
                    }
                }).then((res) => {
                    if (res.data.status === 200) {
                        this.getListRequest();
                    }
                }).catch(() => {});
            },
            onPageChange(pageIndex, pageSize) {
                this.searchParams.pageNo = pageIndex;
                this.searchParams.pageSize = pageSize;
                this.getListRequest();
            },
            onDetailBtn(e) {
                this.dataId = e.id;
                this.detailDialogState = true;
            },
            onVisibleChangeOfDetailDialog(e) {
                if (!e) {
                    this.dataId = null;
                }
                this.detailDialogState = e;
            },
            onFinish() {
                this.saveDialogState = false;
                this.getListRequest();
            },
            onVisibleChange(e) {
                if (!e) {
                    this.dataId = null;
                }
                this.saveDialogState = e;
            },
            /** 查询列表 */
            getListRequest() {
                this.tableLoading = true;
                this.apiItem.page(this.searchParams).then(res => {
                    this.tableLoading = false;
                    this.getStateCountRequest();
                    if (res.data.status === 200) {
                        this.tableData = res.data.res || [];
                        this.totalCount = res.data.count;
                    }
                });
            },
            /** 搜索按钮操作 */
            onSearchBtn() {
                this.searchParams.pageNo = 1;
                this.totalCount = 1;
                this.getListRequest();
            },
            /** 新增按钮操作 */
            onAddBtn() {
                this.saveDialogState = true;
            },
            /** 修改按钮操作 */
            onEditBtn(row) {
                this.dataId = row.id;
                this.saveDialogState = true;
            },
            clearCacheMethod() {
                // Object.assign(this.$data, this.$options.data());
                this.$nextTick(() => {
                    this.getDependentData();
                });
            },
            getStateCountRequest() {
                return machineManagerRepairOrderGetStateCount(this.searchParams).then(res => {
                    if (res.data.status === 200) {
                        const resData = res.data.res || [];
                        this.repairStateList.forEach(x => {
                            x.count = resData.find(k => k.auditState === x.id) ? resData.find(k => k.auditState === x.id).count : null;
                        });
                    }
                });
            },
            async getDependentData() {
                await this.getMenuColumnListRequest();
                await this.getListRequest();
            }
        },
        mounted() {
            this.getDependentData();
        }
    };
</script>
